package com.alittle.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

/**
 * Created by wom on 2015/8/17.
 *
 * <p>缓存，用户的手机号，密码<p/>
 * <p>不知道SharedPreferences直接用默认的，还是自己创建一个</p>
 */


public class ParentCache {

    static ParentCache parentCache;

    private SharedPreferences parentPreferences;

    private String phone;
    private String pwd;

    private static final String KEY_PHONE = "phone";
    private static final String KEY_PWD = "pwd";


    private ParentCache(Context context){

        parentPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    }


    public static ParentCache getInstance(Context context) {

        if(parentCache == null) {
            parentCache = new ParentCache(context.getApplicationContext());
        }
        return parentCache;
    }

    public void clearCache() {
        parentPreferences.edit().clear().apply();
    }

    public String getPhone() {

        if (TextUtils.isEmpty(pwd)) {
            pwd = parentPreferences.getString(KEY_PHONE, null);
        }
        return pwd;
    }

    public String getPwd() {

        if (TextUtils.isEmpty(phone)) {
            phone = parentPreferences.getString(KEY_PHONE, null);
        }
        return phone;
    }

    public boolean setPhone(String phone) {

        SharedPreferences.Editor editor = parentPreferences.edit();

        boolean ret = editor.putString(KEY_PHONE, phone).commit();

        if (ret) {
            this.phone = phone;
        }
        return ret;
    }

    public boolean setPwd(String pwd) {

        SharedPreferences.Editor editor = parentPreferences.edit();

        boolean ret = editor.putString(KEY_PWD, pwd).commit();

        if (ret) {
            this.pwd = pwd;
        }
        return ret;
    }
}
